package com.bfly.mall.product.service.impl;

import com.bfly.core.base.service.BaseServiceImpl;
import com.bfly.mall.product.dao.ProductAttrMapper;
import com.bfly.mall.product.entity.ProductAttr;
import com.bfly.mall.product.dto.ProductAttrFormDTO;
import com.bfly.mall.product.service.IProductAttrService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author 长沙商脉科技有限公司
 * @date 2020/9/21 12:32
 */
@Service
public class ProductAttrServiceImpl extends BaseServiceImpl<ProductAttr, Integer> implements IProductAttrService {

    @Autowired
    private ProductAttrMapper attrMapper;

    @Override
    public List<ProductAttr> getAttrs(int productId) {
        return attrMapper.getAttrs(productId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void merge(int productId, List<ProductAttrFormDTO> formDTO) {
        // 先清空产品属性 然后保存
        attrMapper.clearAttrs(productId);

        Date now = new Date();
        formDTO.forEach(dto -> {
            ProductAttr attr = new ProductAttr();
            BeanUtils.copyProperties(dto, attr);
            attr.setProductId(productId);
            attr.setCreateDate(now);
            attr.setUpdateDate(attr.getCreateDate());
            super.save(attr);
        });
    }
}